//
//  NSURL+QueryDict.m
//  TravelGuideMdd
//
//  Created by 陈曦 on 13-6-20.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "NSURL+QueryDict.h"

@implementation NSURL(QueryDict)

- (NSDictionary*)queryDict
{
    return [NSURL decodedParametersForQuery:self.query];
}

- (NSString*)action
{
    return self.host;
}

-(NSString *)queryValueWithKey:(NSString *)string{
    NSDictionary * queryDict =  [self dictionaryWithUsingEncoding:NSUTF8StringEncoding];
    NSString * value = [queryDict stringValueForKey:string];
    return value;
}

- (NSDictionary*)dictionaryWithUsingEncoding:(NSStringEncoding)encoding {
    NSCharacterSet* delimiterSet = [NSCharacterSet characterSetWithCharactersInString:@"&;"];
    NSMutableDictionary* pairs = [NSMutableDictionary dictionary];
    NSScanner* scanner = [[NSScanner alloc] initWithString:self.query];
    while (![scanner isAtEnd]) {
        NSString* pairString = nil;
        [scanner scanUpToCharactersFromSet:delimiterSet intoString:&pairString];
        [scanner scanCharactersFromSet:delimiterSet intoString:NULL];
        NSArray* kvPair = [pairString componentsSeparatedByString:@"="];
        if (kvPair.count == 2) {
            NSString* key = [[kvPair objectAtIndex:0]
                             stringByReplacingPercentEscapesUsingEncoding:encoding];
            NSString* value = [[kvPair objectAtIndex:1]
                               stringByReplacingPercentEscapesUsingEncoding:encoding];
            [pairs setObject:value forKey:key];
        }
    }
    
    return [NSDictionary dictionaryWithDictionary:pairs];
}

@end
